<template>
  <!-- 书写html结构 只可以有一个div 但是可以嵌套多个div -->
  <div>
    <el-row>
      <el-col :span="4">
        <el-input
          v-model="searchForm.roleName"
          size="mini"
          placeholder="请输入角色名称"></el-input>
      </el-col>
      <el-col :span="4">
        <el-select
          v-model="searchForm.status"
          placeholder="请选职位状态"
          size="mini">
          <el-option label="启用" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button
          type="success"
          icon="el-icon-search"
          size="mini"
          v-has="'role:query'"
          @click="search"
          >搜索</el-button
        >&nbsp;
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          v-has="'role:add'"
          @click="handleAdd"
          >添加</el-button
        >
      </el-col>
      <el-col :span="2">
        <div class="grid-content bg-purple"></div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple-light"></div>
      </el-col>
    </el-row>
    <!-- 表格的列 prop 组件 父作用域向子作用域传值 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column width="110" prop="roleName" label="角色名称">
      </el-table-column>
      <el-table-column width="120" prop="roleKey" label="角色权限字符串">
      </el-table-column>
      <el-table-column
        width="110"
        prop="status"
        :formatter="getStatus"
        label="角色状态">
      </el-table-column>
      <el-table-column
        width="90"
        prop="delFlag"
        :formatter="getStatus2"
        label="删除标志">
      </el-table-column>
      <el-table-column width="99" prop="createBy" label="创建者">
      </el-table-column>
      <el-table-column width="201" prop="createTime" label="创建时间">
      </el-table-column>
      <el-table-column width="99" prop="updateBy" label="更新者">
      </el-table-column>
      <el-table-column width="201" prop="updateTime" label="更新时间">
      </el-table-column>
      <el-table-column width="150" prop="remark" label="备注">
      </el-table-column>
      <el-table-column fixed="right" width="360" label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            v-has="'role:menu'"
            @click="givePerms(scope.$index, scope.row)"
            >角色授权
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            size="mini"
            v-has="'role:flush'"
            @click="refresh"
            >刷新</el-button
          >
          <el-button
            type="primary"
            size="mini"
            v-has="'role:update'"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑
          </el-button>
          <el-button
            type="danger"
            size="mini"
            v-has="'role:delete'"
            plain
            @click="handleDelete(scope.row.roleId)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 6, 12, 36]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- 旅游网权限添加/更新对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-ruleForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色权限字符串" :label-width="formLabelWidth">
          <el-input v-model="form.roleKey" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="显示顺序" :label-width="formLabelWidth">
          <el-input v-model="form.roleSort" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" placeholder="请选部门状态">
            <el-option label="启用" value="0"></el-option>
            <el-option label="禁用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="删除标志" :label-width="formLabelWidth">
          <el-select v-model="form.delFlag" placeholder="请选删除标志">
            <el-option label="存在" value="0"></el-option>
            <el-option label="删除" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" plain @click="addOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!--角色授权弹出框-->
    <el-dialog title="权限菜单" :visible.sync="menuTreeVisible">
      <el-tree
        :data="data"
        :props="defaultProps"
        node-key="id"
        show-checkbox
        check-strictly
        ref="menuTree"
        :check-strictly="true"
        :default-checked-keys="nodeChecked">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRoleAndMenus()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<!--书写组件配置项目  相当于写js代码的地方 -->
<script>
//数据 全是json格式
export default {
  //注册属性 父传子 数据传递
  props: {},
  data() {
    //定义数据
    return {
      data: [], //权限树数组对象
      defaultProps: {
        //父对象传值
        children: "children",
        label: "label",
      },
      nodeChecked: [], //勾选项目数组对象
      roleId: 0, //因为角色ID在不同的js方法种使用，定义为全局的
      menuTreeVisible: false, //权限树是否显示
      tableData: [], //表格数据
      currentPage: 1, //页码 第几页
      pageSize: 3, //每页显示数量
      total: 15, //分页总数量
      searchForm: { roleName: "", status: "" }, //封装查询对象
      dialogFormVisible: false, //是否显示对话框
      title: "角色添加", //默认显示title
      form: {
        roleName: "",
        roleKey: "",
        roleSort: "",
        status: "",
        delFlag: "",
        remark: "",
      }, //form表单
      formLabelWidth: "120px", //labal宽度
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        status: [
          { required: true, message: "请选择角色状态", trigger: "change" },
        ],
        remark: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  //初始化数据
  created() {
    this.loadData();
  },
  //方法书写
  methods: {
    //存放所有使用的方法（函数）
    //封装请求数据的方法
    loadData() {
      //定义变量_this=tshi
      var _this = this;
      //this.$http向后台发请求 --- 分页查询
      this.$http
        .post(
          "/role/queryPage", //请求的url
          {
            pageNo: this.currentPage,
            pageSize: this.pageSize, //currentpage   当前页面
            data: this.searchForm,
          }
        ) //请求参数  json格式
        // {"roleName":this.searchForm.roleName,"status":this.searchForm.status}}
        .then(function (response) {
          //回调函数
          //前端控制台打印  response 是json对象
          console.log(response);
          //JSON.stringify() 将json转换为json字符串 ,方便查看
          console.log(JSON.stringify(response));
          //response获取后台数据时，一定加data  response.data相当于从响应的body中获取
          //判断值是否正确
          if (response.data.code == 200) {
            //这里面直接写this相当于this.$http对象 不是vue
            // this.tableData = response.data.data.list; //错误的
            _this.tableData = response.data.data.records;
            _this.total = response.data.data.total;
          }
        })
        .catch(function (error) {
          //异常处理
          console.log(error);
        })
        .then(function () {
          //总执行 最终处理      类似java  异常处理的finally
          // always executed
        });
    },
    //刷新
    refresh() {
      //原始js重新请求
      location.reload();
    },
    //每页数量发生变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      //调用加载数据方法
      this.loadData();
    },
    //页码（第几页）发生变化
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      //调用加载数据方法
      this.loadData();
    },
    //获取角色状态 把状态数字,转换成字符
    getStatus(row, column, cellValue, index) {
      //cellValue   status的值
      /* var returnValue = '';
             if(cellValue==1){
                 returnValue= "启用";
             }else{
                 returnValue= "禁用";
             }
             return returnValue;*/
      return cellValue == 0 ? "启动" : "禁用";
    },
    //获取数据范围 把状态数字,转换成字符
    getStatus1(row, column, cellValue, index) {
      return cellValue == 1 ? "全部数据权限" : "自定数据权限";
    },
    //获取删除标志 把状态数字,转换成字符
    getStatus2(row, column, cellValue, index) {
      return cellValue == 0 ? "存在" : "删除";
    },

    //搜索方法
    search() {
      this.loadData();
      //搜索时,使页码为1
      this.currentPage = 1;
    },

    //角色授权
    givePerms(index, row) {
      //弹出框，显示权限树，根据该角色对应的权限，让权限树默认勾选响应的值
      //给角色ID复制
      this.roleId = row.roleId;
      //根据角色ID查出权限菜单ID，赋值给nodeChecked
      var _this = this;
      //初始化数据,把菜单树数据加载
      this.$http
        .post("/menu/queryTree") //指定请求的url及参数  get
        .then(function (response) {
          /*   $.ajax(url:'',async:false) //默认同步
                        _this.data=tmpData;*/
          let tmpData = response.data.data;
          // _this.data=response.data.data;W
          //查询并给勾选项赋值
          _this.$http
            .get("/role/queryMenuIdListByRid?roleId=" + _this.roleId)
            .then(function (response) {
              _this.data = tmpData;
              _this.nodeChecked = response.data.data;
            });
        });

      //显示权限菜单对话框
      this.menuTreeVisible = true;
    },

    //添加角色(职位)和权限关联
    addRoleAndMenus() {
      //获取重新选中的节点
      let nodes = this.$refs.menuTree.getCheckedNodes();
      //判断至少选中一个节点
      if (nodes.length < 1) {
        this.$message.error("至少选中一个节点");
        return; // 让代码终止运行
      }
      let tempMenuIds = "";
      //循环遍历
      for (var i = 0; i < nodes.length; i++) {
        tempMenuIds += nodes[i].id + ",";
      }
      //tempMenuIds="100,101,102,200,201,"  拼接后最后加,  去掉最后一个逗号
      tempMenuIds = tempMenuIds.substr(0, tempMenuIds.length - 1);
      //tempMenuIds="100,101,102,200,201"
      // alert("当前角色为："+this.roleId+"，该角色对应新的权限ID为："+tempMenuIds);
      var _this = this;
      //执行后台添加方法
      this.$http
        .post(
          "/role/addPosAndMenu?roleId=" +
            this.roleId +
            "&menuIds=" +
            tempMenuIds
        )
        .then(function (response) {
          console.log(response);
          if (response.data.code == 200) {
            //提示成功
            _this.$message({
              type: "success",
              message: "授权成功!",
            });
            //关闭弹框
            _this.menuTreeVisible = false;
            //重新加载数据
            _this.loadData();
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    },

    //跳转更新
    handleEdit(index, row) {
      //row  当前行数据 如果是第一行  row = {deptId:1,deptName:'管理部',description:'店长的事',status:1}
      console.log(index, row);
      //alert(index+","+JSON.stringify(row));
      //row = {"deptName":'xxx',"loc":'xxx',deptNo:xxx}
      //让对话框显示
      this.dialogFormVisible = true;
      //让title值也发生变化
      this.title = "角色更新";
      //给表单赋值
      this.form = row;
      //把数字1变成字符串1
      this.form.status = row.status + "";
    },
    //跳转添加
    handleAdd() {
      //让对话框显示
      this.dialogFormVisible = true;
      //让title值也发生变化
      this.title = "角色添加";
      //让form清空
      this.form = {};
    },
    //真正添加或者更新
    addOrUpdate() {
      //定义请求路径，默认是添加
      var uri = "/role/add";
      //判断是否是更新
      if (this.title == "角色更新") {
        uri = "/role/update";
      }
      //定义变量_this=tshi
      var _this = this;
      //this.$http向后台发请求
      this.$http
        .post(
          uri, //请求的url
          this.form
        ) //请求参数  json格式
        .then(function (response) {
          //回调函数
          //前端控制台打印  response 是json对象
          console.log(response);
          console.log(JSON.stringify(response));
          //response获取后台数据时，一定加data  response.data相当于从响应的body中获取
          if (response.data.code == 200) {
            //提示成功
            _this.$message({
              message: "恭喜你，这是一条成功消息",
              type: "success",
            });
            //关闭弹框
            _this.dialogFormVisible = false;
            //重新加载数据
            _this.loadData();
          } else {
            _this.$message.error("错了哦，这是一条错误消息");
          }
        })
        .catch(function (error) {
          //异常处理
          console.log(error);
        });
    },

    //处理删除
    handleDelete(roleId) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var _this = this;
        //赋值 this.$http官网代码  this.form =form:{deptName:'',description:'',status:1}
        this.$http
          .delete("/role/deleteById?id=" + roleId)
          .then(function (response) {
            console.log(response);
            if (response.data.code == 200) {
              _this.$message({
                message: "操作成功",
                type: "success",
              });
              _this.dialogFormVisible = false;
              _this.loadData();
              this.currentPage = _this.data.data.pageNo;
            } else {
              _this.$message("操作失败");
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      });
    },
  },
  //声明注解
  components: {},
};
</script>
